package org.example;

import org.example.target.DataOperator;
import org.example.target.DataOperator2;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

public class Main {
    public static void main(String[] args) {
        //对象适配器
        DataOperator dataOperator = getAdapterBean();
        System.out.println(dataOperator.doEncrypt(2, "abcdefg"));

        /**
         * 类适配器
         * 将getAdapterBean()方法的返回值修改为DataOperator2
         * 同时将方法内部return的类型强转为DataOperator2
         * 方法内获得properties的字段换成newAdapter
         */
//        DataOperator2 dataOperator2 = getAdapterBean();
//        System.out.println(dataOperator2.doEncrypt(2, "abcdefg"));
    }

    static DataOperator getAdapterBean(){
        try {
            //get name
            String filePath = "AdapterPattern\\src\\main\\resources\\adapter.properties";
            Properties properties = new Properties();
            properties.load(new FileReader(filePath));
            String adapter = "org.example.adapter." + properties.getProperty("oldAdapter");

            //instantiate bean
            Class c = Class.forName(adapter);
            Constructor constructor = c.getConstructor(null);
            return (DataOperator) constructor.newInstance();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}